package study.spring.ajax;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import contact.ContactDAO;
import entities.Contact;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	@Autowired
	private ContactDAO contactDAO;
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@Transactional
	@RequestMapping(value = "/")
	public ModelAndView home() {
		ModelAndView model = new ModelAndView("home");
		model.addObject("contacts", contactDAO.listContact());
		return model;
	}
	
	@Transactional
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public Contact saveContact(Contact contact){
		contactDAO.saveOrUpdate(contact);
		return contact;
	}
	
	@Transactional
	@RequestMapping(value = "getJson/{firstname}/{lastname}", method = RequestMethod.GET )
	@ResponseBody
	public List<Contact> findByName(@PathVariable("firstname") String first, @PathVariable("lastname") String last){
		List<Contact> list = contactDAO.getByName(first, last);
		return list;
	}
	
	@Transactional
	@RequestMapping(value = "load", method = RequestMethod.GET) 
	public ModelAndView load(){
		ModelAndView model = new ModelAndView("table");
		return model;
	}
	
	@Transactional
	@RequestMapping(value = "load/{searchName}", method=RequestMethod.GET)
	public ModelAndView loadByName(@PathVariable("searchName") String firstname){
		ModelAndView model = new ModelAndView("search");
		model.addObject("contacts", contactDAO.getByFirstName(firstname));
		return model;
	}
}
